<template>
  <el-dialog v-model="isShow" draggable width="720" @close="close" :close-on-click-modal="false">
    <template #header>
      {{data.title}}
    </template>
    <!-- <p>{{data.ids}}</p> -->
    <div class="content">
      <i class="title" v-if="hasStr(data.flag,'device_')">当前选中{{data.data.length}}设备</i>
      <div class="names scroll-base" v-if="hasStr(data.flag,'device_')">
        <el-tag class="name" closable @close="delBatchItem(item.Id)"
          :type="item.alarm?'danger':'success'" 
          v-for="item in data.data" :key="item.Id">
          {{item.sn}}<b v-if="data.flag=='device_system'">[{{item.current_version}}]</b>
        </el-tag>
      </div>
      <div class="item" v-if="'device_factory'.indexOf(data.flag) >= 0">
        <el-form-item label="项目单编号">
          <el-input v-model="data.orderNo" placeholder="请输入项目单编号" style="width: 200px;"/>
        </el-form-item>
        <!-- <el-form-item v-if="data.orderNos.length > 1">
          <el-text type="danger">当前选择记录存在多条项目单编号</el-text>
        </el-form-item> -->
      </div>
      <div class="item" v-if="'device_factory'.indexOf(data.flag) >= 0"> 
        <el-form-item label="选择设备型号">
          <el-select
            v-model="modelName"
            filterable
            remote
            reserve-keyword
            placeholder="输入设备型号关键字查询"
            @click="getModel('')"
            remote-show-suffix
            :remote-method="getModel"
            :loading="loading"
            @change="modelChange"
            :disabled="hasStr('status,unbind',data.flag)"
          >
            <el-option
              v-for="item in modelOptions"
              :key="item.Id"
              :label="item.model"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="item" v-if="'device_factory,device_list'.indexOf(data.flag) >= 0"> 
        <el-form-item label="选择所属用户">
          <el-select
            v-model="clientName"
            filterable
            remote
            reserve-keyword
            placeholder="输入用户名称关键字查询"
            @click="getClientByName('')"
            remote-show-suffix
            :remote-method="getClientByName"
            :loading="loading"
            @change="clientChange"
            :disabled="hasStr('status,unbind',data.flag)"
          >
            <el-option
              v-for="item in clientOptions"
              :key="item.Id"
              :label="item.name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </div>
      <!-- <div class="item" v-if="'device_factory,device_list'.indexOf(data.flag) >= 0"> 
        <el-form-item label="批量设置设备状态为">
          <el-button type="danger" @click="msgBox(cStatus[1].v,'修改状态为'+cStatus[1].t)" style="margin: 0;border-radius:5px 0 0 5px;" :loading="loading">{{cStatus[1].t}}</el-button>
          <el-button type="success" @click="msgBox(cStatus[0].v,'修改状态为'+cStatus[0].t)" style="margin: 0;border-radius: 0 5px 5px 0;" :loading="loading">{{cStatus[0].t}}</el-button>
        </el-form-item>
      </div> -->
      <!-- 远程升级&远程恢复出厂设置 -->
      <div class="item" v-if="'device_system'.indexOf(data.flag) >= 0">
        <p>
          <el-tag>设备所用固件</el-tag>  {{romLastInfo.name}}
        </p>
        <p>
          <el-tag type="success">固件文件名</el-tag>  {{romLastInfo.file}}
        </p>
        <p v-if="!isNull(romLastInfo.lastVersion)">
          <el-tag type="danger">固件最新版本</el-tag>  
          {{romLastInfo.lastVersion.edition}}[{{romLastInfo.lastVersion.version}}]
          <i style="color: #999;">{{romLastInfo.lastVersion.remark}}</i>
        </p>
      </div>
      <!-- 应用管理 -->
      <div class="table" v-if="data.flag == 'device_app'">
        <el-table :data="devAppList" border height="350" :loading="loading">
          <el-table-column label="应用" fixed="left" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-button class="row-inline" type="success" size="small" @click="devAppAction('install', scope.row)">安装应用</el-button>
              <!-- <img class="row-inline" :src="scope.row.appicon" style="width: 32px;height: 32px;"/> -->
              <span class="row-inline" style="margin: 0 10px;">{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column property="remark" label="应用说明" width="200" sortable :show-overflow-tooltip="true"></el-table-column>
          <el-table-column property="version" label="版本" width="100" sortable :show-overflow-tooltip="true"></el-table-column>          
        </el-table>
      </div>
      <div class="table" v-if="hasStr('uninstall,autorun',data.flag)">
        <el-table :data="devAppList" border height="350" :loading="loading">
          <el-table-column label="应用" fixed="left" :show-overflow-tooltip="true">
            <template #default="scope">
              <span v-if="data.flag == 'autorun'">
                <el-button v-if="hasStr(scope.row.name,'开机自启动')" class="row-inline" size="small" @click="devAppAction('autorun_off', scope.row)">取消开机自启</el-button>
                <el-button v-else class="row-inline" type="primary" size="small" @click="devAppAction('autorun_on', scope.row)">设置开机自启</el-button>
              </span>
              <el-button v-else class="row-inline" type="danger" size="small" @click="devAppAction('uninstall', scope.row)">卸载应用</el-button>
              <!-- <img class="row-inline" :src="scope.row.appicon" style="width: 32px;height: 32px;"/> -->
              <span class="row-inline" style="margin: 0 10px;">{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column property="versionName" label="版本" width="100" sortable :show-overflow-tooltip="true"></el-table-column>
          <el-table-column property="dtInstall" label="安装日期" width="200" sortable :show-overflow-tooltip="true"></el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="footer" v-if="hasStr('device_system,device_reset',data.flag)" style="padding: 0;padding-bottom: 15px">
        <el-switch size="large" v-model="switchBtn.value" :active-text="switchBtn.onTxt" :inactive-text="switchBtn.offTxt" />
      </div>
      <div class="footer">
        <el-button @click="close()">关  闭</el-button>
        <el-button @click="done()" type="primary" v-if="hasStr('device_factory,device_list',data.flag)">设置</el-button>
        <el-button @click="devUpdateCheck('update')" type="warning" v-if="data.flag == 'device_system'">系统升级</el-button>
        <el-button @click="msgBox('factory','即将对所选设备恢复出厂设置',null)" type="danger" v-if="data.flag == 'device_system'">恢复出厂设置</el-button>
        <el-button @click="sendCommand('animation',null)" type="success" v-if="data.flag == 'device_system'">设置开机动画测试</el-button>
        <el-button @click="msgBox('reset','即将对所选设备进行远程重启',null)" type="warning" v-if="data.flag == 'device_reset'">远程重启</el-button>
        <el-button @click="msgBox('powerdown','即将对所选设备进行远程关机',null)" type="danger" v-if="data.flag == 'device_reset'">远程关机</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue-demi";
import { ElMessageBox, ElNotification } from 'element-plus';
import util from '@/assets/js/util';
import mqtt from '@/assets/js/mqtt';
import http from '@/axios/http';
export default {
  setup(props, ctx) {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let t = r.msgType
          let d = r.data.data
          // console.log(d)
          if (t == 123 || t == 124) {
            ctx.emit("done", d);
            isShow.value = false;
          }
          if (t == 61) {
            clientOptions.value = d
          }
          if (t == 165) {
            modelOptions.value = d
          }
          if (t == 154) {
          //console.log(d)
            let rli = {}
            rli.id = d[0].Id
            rli.name = d[0].firmware_name
            rli.file = d[0].firmware_file_name
            let ei = d[0].edition_infos
            if (ei && ei.length >=1) rli.lastVersion = ei[ei.length-1]
            romLastInfo.value = rli
          }
          if (t == 208) {
            devAppList.value = d[0]?d[0].apps:[]
          }
          if (t >= 90020 && t <= 90024) {
          //console.log(t,d)
          }
          if (t >= 50032 && t <= 50034) {
          //console.log(t,d)
          }
        }
      })
    }
    let isShow = ref(false);
    let loading = ref(false)
    let data = reactive({
      flag: '',
      title: '',
      ids: [],
      boardSNs: [],
      data: [],
      clients: [],
      models: [],
      orderNos: [],
      status: '',
      orderNo: '',
      equipment_model: {},
      plat_user: {}
    })


    function open(e) {
    //console.log(e)
      mqttOnMsg()
      switchBtn.value = true
      let m = ''
      data.flag = e.flag
      data.data = e.data
      let d = e.data
      if (d.length > 0) {
        let ids = [],clients = [],orderNos = [],boardSNs = [],models = []
        for(let i in d) {
        //console.log(d[i])
          ids.push(d[i].Id)
          boardSNs.push(d[i].borad_sn)
          clients.push(d[i].plat_user.name)
          orderNos.push(d[i].project_list_number)
          models.push(d[i].equipment_model.Id)
          // d[i].alarm = false
          // if (!util.hasStr('device_list,device_factory',data.flag) && d[i].on_offline < 1) m = '请选择在线设备进行操作'
        }
        data.ids = util.distinctArr(ids)
        data.boardSNs = util.distinctArr(boardSNs)
        data.clients = util.distinctArr(clients)
        if ( hasStr('device_app,unstaill,autorun,device_system',data.flag) && data.clients.length > 1) m = '请选择同一用户下的设备进行操作'
        data.models = util.distinctArr(models)
        if ( hasStr('device_system',data.flag) && data.models.length > 1) m = '请选择同一型号的设备进行操作'
        data.orderNos = util.distinctArr(orderNos)
      //console.log(data.orderNos,orderNos)
        if ( hasStr('device_factory',data.flag) && data.orderNos.length > 1) m = '请选择同一项目单编号的设备进行操作'
        data.orderNo = ''//data.orderNos[0] || ''
        data.equipment_model = {}
        data.plat_user = {}
        modelName.value = ''
        clientName.value = ''
      } else {
        m = '请先选择记录'
      }
      if (isNull(m)) {
        if (hasStr('device_factory',data.flag)) {
          data.title = '终端设备出厂设置'
        } else {
          // data.orderNo = data.data[0].project_list_number
          data.equipment_model = data.data[0].equipment_model
          data.plat_user = data.data[0].plat_user
          // modelName.value = data.data[0].equipment_model.model
          // clientName.value = data.data[0].plat_user.name
          if (hasStr('device_list',data.flag)) {
            data.title = '设置终端所属用户'
          }
          if (data.flag == 'device_app') {
            data.title = '批量安装应用'
            if (d[0]) getDevAppList(d[0].plat_user_id)
          }
          if (data.flag == 'uninstall') {
            data.title = '卸载应用'
            if (d[0]) devAppList.value = d[0].installed_apps
          }
          if (data.flag == 'autorun') {
            data.title = '设置应用开机自启动'
            if (d[0]) devAppList.value = d[0].installed_apps
          }
          if (data.flag == 'device_system') {
            data.title = '系统固件升级恢复出厂设置'
            if (d[0]) getRomInfo(d[0].equipment_model.firmware_id)
          }
           if (data.flag == 'device_reset') {
            data.title = '远程重启关机'
          }
        }
        isShow.value = true;
      } else {
        ElNotification({
          type: 'warning',
          title: '批量管理设备',
          message: m
        })
      }
    }

    function close() {
      isShow.value = false;
      ctx.emit("done", null);
    }

    function done() {
      let err = ''
      if (data.flag == 'device_factory') {
        if (util.isNull(data.ids)) err = '设备ID有误，请重新选择'
        else if (util.isNull(data.orderNo)) err = '项目单编号不能为空'
        else if (util.isNull(data.equipment_model.Id)) err = '设备型号不能为空'
        else if (util.isNull(data.plat_user.Id)) err = '所属用户不能为空'
        else if (data.boardSNs.length != data.data.length) {
          err = '有未绑定主板的设备'
          let d = data.data
          for(let i in d) {
          //console.log(d[i])
            d[i].alarm = isNull(d[i].borad_sn)
          }
        } else if (
          !data.equipment_model.firmware || 
          !data.equipment_model.firmware.edition_infos ||
          !data.equipment_model.firmware.edition_infos[0] || 
          !data.equipment_model.firmware.edition_infos[0].version
          ) {
            err = '当前设备型号固件版本信息为空'
        }
      }
      if (data.flag == 'device_list') {
        if (util.isNull(data.plat_user.Id)) err = '所属用户不能为空'
        else if (data.boardSNs.length != data.data.length) {
          err = '有未绑定主板的设备'
          let d = data.data
          for(let i in d) {
            d[i].alarm = isNull(d[i].borad_sn)
          }
        }
      }
      if (!util.isNull(err)) {
        ElNotification({
            type: 'warning',
            duration: 1500,
            title: '',
            message: err
          })
        return
      }
      loading.value = true
      if (hasStr('device_factory,device_list',data.flag)) {
        let msgCode = 0
        let m = {}
        m.ids = data.ids.toString()
        m.user_id = data.plat_user.Id
        if (data.flag == 'device_factory') {
          msgCode = 123
          m.project_list_number = 'NO.'+data.orderNo
          m.equipment_model_id = data.equipment_model.Id
          m.current_version = data.equipment_model.firmware.edition_infos[0].version
          m.status = 0
          // m.terminal_type = ''
        }
        if (data.flag == 'device_list') {
          msgCode = 124
        }
        let topic = mqtt.TOPIC_REQ+msgCode
        let p = {}
        p.msgType = msgCode
        p.clientId = user.id
        p.userName = user.username
        p.message = m
      //console.log(data.flag+'设备:',JSON.stringify(p))
        mqtt.publish(topic,JSON.stringify(p))
      }
    }

    function delBatchItem(id) {
      let d = data.data
      for(let i in d) {
        if (id == d[i].Id) {
          d.splice(i,1)
          data.ids.splice(i,1)
        }
      }
    }

    // 是否需要终端确认
    let switchBtn = reactive({
      value: false,
      onTxt: '需要终端确认后执行指令',
      offTxt: '终端直接执行指令',
    })

    // 合并查询用户应用列表及已安装的应用列表
    let devAppList = ref([])
    function getDevAppList(cid) {
      loading.value = true
      let msgCode = 208
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.plat_user_id = cid
      m.status = 0
      m.indexPage = 1
      m.pageSize = 50
      g.message = m
    //console.log('查询用户应用列表：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 查询固件信息
    let romLastInfo = ref([])
    function getRomInfo(rId) {
      let msgCode = 154
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.id = rId
      g.message = m
    //console.log('查询固件byId',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 查询设备型号
    let modelName = ref("")
    let modelOptions = ref([])
    async function getModel(query) {
      let msgCode = 165
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.model = query
      m.indexPage = 1
      m.pageSize = 10
      g.message = m
      mqtt.publish(topic,JSON.stringify(g))
    }
    function modelChange(e) {
      let mo = modelOptions.value
      for (let i in mo) {
        if (e == mo[i].Id) {
          data.equipment_model = mo[i]
        }
      }
    }
    // 查询用户信息
    let clientName = ref("")
    let clientOptions = ref([])
    function getClientByName(query) {
      let msgCode = 61
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.name = query
      if (user.power > 90) m.scope_length = 8
      m.indexPage = 1
      m.pageSize = 10
      g.message = m
      // console.log('查询用户：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    function clientChange(e) {
      let co = clientOptions.value
      for (let i in co) {
        if (e == co[i].Id) {
          data.plat_user = co[i]
        }
      }
    }

    // 应用管理处理
    function devAppAction(flag,app) {
    //console.log(flag,app)
      let msg = ""
      if (flag == 'install') {
        msg = '即将对所选设备安装【'+app.name+'】'
      }
      if (flag == 'uninstall') {
        msg = '即将对所选设备卸载【'+app.name+'】'
      }
      if (flag == 'autorun_off') {
        msg = '即将对所选设备取消【'+app.name+'】开机自启动'
      }
      if (flag == 'autorun_on') {
        msg = '即将对所选设备设置【'+app.name+'】开机自启动'
      }
      msgBox(flag, msg, app)
    }
  
    // 固件升级处理
    function devUpdateCheck(flag) {
      let msg = ""
      let d = data.data
      let mId = ""
      for(let i in d) {
        if (i==0) mId = d[i].equipment_model_id
        else {
          d[i].alarm = mId != d[i].equipment_model_id
          if (d[i].alarm) msg = "设备型号不同的终端不能批量升级"
        }
      }

      let romId = ''
      let rli = romLastInfo.value
      if (isNull(msg)) {
        for(let i in d) {
          if (i==0) {
            romId = d[i].equipment_model.firmware_id
          }
          else {
            d[i].alarm = romId != d[i].equipment_model.firmware_id
            if (d[i].alarm) msg = "固件版本不同的终端不能批量升级"
          }
          if (isNull(rli.lastVersion)) {
            msg = "获取固件版本失败"
          } else {
            if (rli.lastVersion.version == d[i].current_version) {
              d[i].alarm = true
              msg = "当前设备系统固件已是最新版"
            }
          }  
        }
      }
            
      if (isNull(msg)) {
        msgBox(flag,'即将对所选设备进行系统升级',rli);
      } else {
        ElNotification({
          title: "请检查不符合要求的终端设备",
          message: msg,
          type: "warning",
          duration: 2000,
        });
      }
    }

    // 确认msgBox
    function msgBox(flag,msg,addData) {
      ElMessageBox.confirm(msg, '是否确认？', {
        confirmButtonText: '确认',
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let commandFlags = 'update,factory,reset,powerdown,install,uninstall,autorun_on,autorun_off'
          if (hasStr(commandFlags,flag)) sendCommand(flag,addData);
        })
        .catch(() => {});
    }

    // 发送设备管理指令
    function sendCommand(f,d) {
    //console.log(f,d)
      let msgCode = 0
      let m = {}
      m.equipment_board_sns = data.boardSNs.toString()
      m.plat_user_id = data.plat_user.Id
      m.isConfirm = switchBtn.value
      if (f=='update') {
        msgCode = 90020  // 系统升级
        m.equipment_model_id = data.equipment_model.Id
        m.version = d.lastVersion.version 
      }
      if (f=='factory') {
        msgCode = 90021 // 恢复出厂设置
        m.time = util.formatDateTime(new Date())
      }
      if (f=='powerdown') {
        msgCode = 90022 // 关机
        m.time = util.formatDateTime(new Date())
      }
      if (f=='reset') {
        msgCode = 90023 // 重启
        m.time = util.formatDateTime(new Date())
      }
      if (f=='animation') {
        msgCode = 90024 // 开机动画测试
        m.time = util.formatDateTime(new Date())
      }
      if (f=='install') {
        msgCode = 50032 // 安装应用
        m.package_name = d.package_name
        m.version = d.version
        m.ver_order = d.ver_order
        m.isConfirm = false
      }
      if (f=='uninstall') {
        msgCode = 50033 // 卸载应用
        m.package_name = d.packageName
        m.version = d.versionName
        m.ver_order = d.versionCode
        m.isConfirm = false
      }
      if (f=='autorun_on' || f=='autorun_off') {
        msgCode = 50034 // 应用开机自启动
        m.package_name = d.packageName
        m.version = d.versionName
        m.ver_order = d.versionCode
        m.isAutoRun = f=='autorun_on'
      }
      let topic = mqtt.TOPIC_REQ+msgCode
      let p = {}
      p.msgType = msgCode
      p.clientId = user.id
      p.userName = user.username
      p.message = m
    //console.log(f+'设备:',JSON.stringify(p))
      mqtt.publish(topic,JSON.stringify(p))
    }

    function isNull(v) {
      return util.isNull(v)
    }
    function hasStr(S,k) {
      return util.hasStr(S,k)
    }

    return {
      user, isShow, loading, data, 
      open, close, done, delBatchItem, switchBtn,
      devAppList,romLastInfo, modelName, modelOptions, getModel, modelChange, 
      clientName, clientOptions, getClientByName, clientChange, 
      devAppAction, devUpdateCheck, msgBox, sendCommand, isNull, hasStr
    };
  },
};
</script>

<style lang="scss" scoped>
.content{
  width: 100%;
  .title{
    font-style: normal;
  }
  .names {
    padding: 5px;
    max-height: 90px;
    overflow-y: auto;
    .name {
      margin: 3px;
    }
  }
  .item{
    padding: 10px 0;
    padding-left: 90px;
    .el-form-item{
      margin: 0;
    }
  }
  .table{
    padding: 0;
    .row-inline{
      vertical-align: middle;
    }
  }
  .row{
    display: flex;
    flex-direction: row;
    .danger{
      color: $color-error;
    }
  }
}
.footer{
  @extend %view-flex;
  flex-direction: row;
}
</style>